package nirvana.core.bean.json.file.filePath;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import nirvana.core.bean.json.file.storage.impl.AliOssFileStorage;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 【描 述】：
 * 【环 境】：J2SE 11
 * 【详 细】：
 *
 * @author 李松林
 * @version v1.0 2023-02-01 新建
 * @since 2023-02-01
 */
@Component
@ConditionalOnProperty(value = "fileStorageModel",havingValue = "oss")
public class OssFilePathDeserializer extends JsonDeserializer<String> {

    private final AliOssFileStorage fileStorage;

    public OssFilePathDeserializer(AliOssFileStorage fileStorage) {
        this.fileStorage = fileStorage;
    }


    /**
     * 在反序列化时，起初域名与访问链接，只保留相对路径
     * @param jsonParser
     * @param ctxt
     * @return
     * @throws IOException
     * @throws JacksonException
     */
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JacksonException {

        String path = jsonParser.getText();
        if (StringUtils.hasText(path)){
            String dismantlingPath = fileStorage.dismantlingPath(path);
            return dismantlingPath;
        }
        return path;
    }
}
